/**
 * @Project： Lqyd_Android
 * @Title：QyReaderApp
 * @Description：
 * @Author：wayne
 * @Date：2014年8月7日下午11:53:22
 */
package com.shwread.android.qysw;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

import com.NewActionHelp;
import com.TrainActionHelp;
import com.ciko.code.bean.UserBean;
import com.ciko.code.constant.Constants;
import com.mywork.WorkUIKit;
import com.netease.nim.demo.NimCache;
import com.netease.nim.demo.main.activity.NimAVChatActivity;
import com.netease.nim.demo.session.SessionManager;
import com.netease.nim.demo.util.SystemUtil;
import com.netease.nim.demo.util.storage.StorageUtil;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.SDKOptions;
import com.netease.nimlib.sdk.StatusBarNotificationConfig;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.avchat.AVChatManager;
import com.netease.nimlib.sdk.avchat.model.AVChatData;
import com.shwread.android.qysw.activity.BookShelfActivity;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw.activity.NewLoginActivity;
import com.shwread.android.qysw.step.model.UserHealthyDataModel;
import com.shwread.android.qysw10000241.R;
import com.shwread.android.ui.dialog.SingleSignOnDialog;
import com.shwread.http.util.HttpResponseConfig;
import com.shwread.httpsdk.util.NetUtil;

import net.nightwhistler.htmlspanner.FontFamily;
import net.nightwhistler.pageturner.Configuration;

import org.geometerplus.zlibrary.ui.android.library.ZLAndroidApplication;

import java.util.Stack;

import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.dao.UserDao;
import logic.util.AppUtils;
import logic.util.SDcardUtil;
import logic.util.ScreenUtil;
import logic.util.Util;
import logic.util.logutil.LogUtil;


public class QyReaderApp extends ZLAndroidApplication {

    public static QyReaderApp application;

    public static QyReaderApp getApplication() {
        return application;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        application = this;
        //sd卡初始化
        SDcardUtil.init();
        //activity上下文用获取初始化
        registerActivityLifecycleCallbacks(activityLifecycleCallbacks);
        initReceiver();
//		MultiDex.install(this);
        WorkUIKit.init(this);
        UserHealthyDataModel.getInstance().init();
        //初始化日志类
        LogUtil.isApplicationDebug(this);
        LogUtil.onError(this);

        //初始化屏幕数据
        ScreenUtil.GetInfo(this);

        //初始化云信相关数据
        StorageUtil.init(this, null);
        NimCache.setContext(this);
        NIMClient.init(this, getLoginInfo(), getOptions());

        HttpResponseConfig.CONTEXT = this;
        HttpResponseConfig.EXCEPTION_LOGIN_CODE = DefaultConsts.EXCEPTION_LOGIN_CODE;
        HttpResponseConfig.EXCEPTION_LOGIN_STRING = DefaultConsts.EXCEPTION_LOGIN_STRING;
        HttpResponseConfig.PARAMS_EMPTY_CODE = DefaultConsts.PARAMS_EMPTY_CODE;
        HttpResponseConfig.PARAMS_EMPTY_STRING = DefaultConsts.PARAMS_EMPTY_STRING;
        HttpResponseConfig.PACKAGE_NAME = AppUtils.getPackageName(this);
        NewActionHelp.init(NetUtil.getImei(this), NetUtil.getPsdnIp(), Const.SERVER_URL.equals("http://42.121.255.69:8080/hzlqswserver"));
        NewActionHelp.setEnterpriseId(Constants.enterprise_num);
        NewActionHelp.setClientType(Const.CLIENTTYPE);
        NewActionHelp.initLion(true);
        TrainActionHelp.init(NetUtil.getImei(this), NetUtil.getPsdnIp(), Const.TRAIN_URL.equals("http://42.121.253.209:8081/lqsw_website/"));
        TrainActionHelp.setEnterpriseId(Constants.enterprise_num);
        TrainActionHelp.setClientType(Const.CLIENTTYPE);

        //		// 在IntentFilter中选择你要监听的行为
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);// sd卡被插入，且已经挂载
        intentFilter.setPriority(1000);// 设置最高优先级
        registerReceiver(new SDBroadcastReceiver(), intentFilter);// 注册监听函数

        if (inMainProcess()) {
            // init pinyin
            //            PinYin.init(this);
            //            PinYin.validate();

            // 开启/关闭通知栏消息提醒
            NIMClient.toggleNotification(true);
            SessionManager.init();
            enableAVChat();
        }

        initFontfamily();


//        播放视频用到的
//        initUniversalImageLoader();
//        JCVideoPlayer.setThumbImageViewScalType(ImageView.ScaleType.FIT_XY);
    }


//    private void initUniversalImageLoader() {
//        DisplayImageOptions options = new DisplayImageOptions.Builder()
//                .showImageOnLoading(new ColorDrawable(Color.parseColor("#f0f0f0")))
//                .resetViewBeforeLoading(true)
//                .cacheInMemory(true)
//                .cacheOnDisk(true)
//                .considerExifParams(true)
//                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
//                .bitmapConfig(Bitmap.Config.RGB_565)
//                .build();
//
//        int memClass = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE))
//                .getMemoryClass();
//        int memCacheSize = 1024 * 1024 * memClass / 8;
//
//        File cacheDir = new File(Environment.getExternalStorageDirectory().getPath() + "/jiecao/cache");
//        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
//                .threadPoolSize(3)
//                .threadPriority(Thread.NORM_PRIORITY - 2)
//                .denyCacheImageMultipleSizesInMemory()
//                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
//                .memoryCache(new UsingFreqLimitedMemoryCache(memCacheSize))
//                .memoryCacheSize(memCacheSize)
//                .diskCacheSize(50 * 1024 * 1024)
//                .tasksProcessingOrder(QueueProcessingType.LIFO)
//                .diskCache(new UnlimitedDiskCache(cacheDir))
//                .imageDownloader(new BaseImageDownloader(this, 5 * 1000, 30 * 1000))
//                .defaultDisplayImageOptions(options)
//                .build();
//        ImageLoader.getInstance().init(config);
//    }

    private void enableAVChat() {
        registerAVChatIncomingCallObserver(true);
    }

    private void registerAVChatIncomingCallObserver(boolean register) {
        AVChatManager.getInstance().observeIncomingCall(new Observer<AVChatData>() {
            @Override
            public void onEvent(AVChatData chatData) {
                String account;
                UserBean user = UserDao.getInstance(getApplicationContext()).getLastLoginUser();
                if (user == null) {
                    account = NimCache.getAccount();
                } else {
                    account = user.getImAccount();
                }
                NimAVChatActivity.launch(getApplicationContext(), account, chatData.getAccount(), chatData.getChatType().getValue(), false);
            }
        }, register);
    }

    public static class SDBroadcastReceiver
            extends
            BroadcastReceiver {

        public SDBroadcastReceiver() {
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("android.intent.action.MEDIA_MOUNTED"))// SD
            // 卡已经成功挂载
            {
                SDcardUtil.init();
            }
        }

    }

    private SDKOptions getOptions() {
        SDKOptions options = new SDKOptions();

        // 如果将新消息通知提醒托管给SDK完成，需要添加以下配置。
        // 其中notificationSmallIconId必须提供
        StatusBarNotificationConfig config = new StatusBarNotificationConfig();
        config.notificationEntrance = MainActivity.class;
        config.notificationSmallIconId = R.drawable.ic_launcher;
        options.statusBarNotificationConfig = config;
        NimCache.setConfig(config);

        // 配置保存图片，文件，log等数据的目录
        String sdkPath = Environment.getExternalStorageDirectory() + "/" + getPackageName() + "/nim";
        options.sdkStorageRootPath = sdkPath;

        // 配置数据库加密秘钥
        options.databaseEncryptKey = "NETEASE";

        // 配置是否需要预下载附件缩略图
        options.preloadAttach = true;

        // 配置附件缩略图的尺寸大小，
        options.thumbnailSize = ScreenUtil.screenMin / 2;

        return options;
    }

    private LoginInfo getLoginInfo() {
        //        String account = Preferences.getUserAccount();
        //        String token = Preferences.getUserToken();
        //
        //        if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(token)) {
        //            DemoCache.setAccount(account);
        //            // open db
        //            DatabaseManager.getInstance().open(this);
        //            return new LoginInfo(account, token);
        //        } else {
        return null;
        //        }
    }

    public boolean inMainProcess() {
        String packageName = getPackageName();
        String processName = SystemUtil.getProcessName(this);
        return packageName.equals(processName);
    }

    private static FontFamily kaiFontFamily;

    public static FontFamily getFontFamily() {
        return kaiFontFamily;
    }

    private void initFontfamily() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Typeface basic = Typeface.createFromAsset(getAssets(), "fonts/" + Configuration.CN_FONT_KAITI + ".ttf");
                kaiFontFamily = new FontFamily(Configuration.CN_FONT_KAITI, basic);
            }
        }).start();
    }

    /**
     * 接收用户异常登录的广播
     */
    private LoginReceiver receiver;
    private SingleSignOnDialog dialog;

    private void initReceiver() {
        receiver = new LoginReceiver();
        registerReceiver(receiver, new IntentFilter(DefaultConsts.EXCEPTION_LOGIN_STRING));
    }

    private class LoginReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            Log.e("111111", "sss");
            try {
                if (dialog == null || !dialog.isShowing()) {
                    String json = arg1.getStringExtra("json");
                    String packageName = arg1.getStringExtra("packageName");
                    if (Util.isNotEmpty(packageName)
                            && packageName.equals(AppUtils.getPackageName(arg0))
                            && Util.isNotEmpty(json)
                            && !(getCurrentActivity() instanceof NewLoginActivity)////登录界面屏蔽抢登
                            && !BookShelfActivity.OFFINE_READ) {//离线阅读状态下屏蔽抢登
                        //测试地址的白名单帐号屏蔽抢登提示框
                        if (!"18989898989".equals(NewActionHelp.getAccount())) {
                            LogUtil.e(DefaultConsts.TAG, "接收到广播：帐号在别处登录，" + json);
                            dialog = new SingleSignOnDialog(getCurrentActivity());
                            dialog.setJson(json);
                            dialog.setCancelable(false);
                            dialog.show();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("1111111", e.toString());
            }
        }
    }

    public Stack<Activity> store = new Stack<>();

    /**
     * 获取到当前activity
     */
    public Activity getCurrentActivity() {
        return store.lastElement();
    }

    /**
     * activity上下文引用获取
     */
    ActivityLifecycleCallbacks activityLifecycleCallbacks = new ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            store.add(activity);
            Log.d(getSimpleClassName(activity), String.format("----->onCreate (%s.java:0)", getSimpleClassName(activity)));
        }

        @Override
        public void onActivityDestroyed(Activity activity) {
            store.remove(activity);
            Log.d(getSimpleClassName(activity), String.format("----->onDestroy (%s.java:0)", getSimpleClassName(activity)));
        }

        @Override
        public void onActivityStarted(Activity activity) {
            Log.d(getSimpleClassName(activity), String.format("----->onStart (%s.java:0)", getSimpleClassName(activity)));
        }

        @Override
        public void onActivityResumed(Activity activity) {
            Log.d(getSimpleClassName(activity), String.format("----->onResume (%s.java:0)", getSimpleClassName(activity)));
        }

        @Override
        public void onActivityPaused(Activity activity) {
            Log.d(getSimpleClassName(activity), String.format("----->onPause (%s.java:0)", getSimpleClassName(activity)));
        }

        @Override
        public void onActivityStopped(Activity activity) {
            Log.d(getSimpleClassName(activity), String.format("----->onStop (%s.java:0)", getSimpleClassName(activity)));
        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
            Log.d(getSimpleClassName(activity), String.format("----->SaveInstanceState (%s.java:0)", getSimpleClassName(activity)));
        }
    };

    /**
     * 退出软件
     */
    public void exitApp() {
        clearActivity();
        /*
         * finish()：结束当前Activity，不会立即释放内存。遵循android内存管理机制
         * exit()：结束当前组件如Activity，并立即释放当前Activity所占资源
         * killProcess()：结束当前组件如Activity，并立即释放当前Activity所占资源
         * restartPackage()：结束整个App，包括service等其它Activity组件
         */
        System.exit(0);
    }

    public void clearActivity() {
        if (store != null) {
            synchronized (this) {
                //遍历所有activity进行finish
                for (Activity activity : store) {
                    if (activity != null && !activity.isFinishing()) {
                        activity.finish();
                    }
                }
            }
        }
    }

    private static String getSimpleClassName(Activity activity) {
        String name = activity.getLocalClassName();
        int lastIndex = name.lastIndexOf(".");
        return name.substring(lastIndex + 1);
    }

    @Override
    public void onTerminate() {
        // 程序终止的时候执行
        unregisterReceiver(receiver);
        super.onTerminate();
    }

    @Override
    public void onLowMemory() {
        // 低内存的时候执行
        super.onLowMemory();
    }

    @Override
    public void onTrimMemory(int level) {
        // 程序在内存清理的时候执行
        super.onTrimMemory(level);
    }
}
